//
//  MineVC.swift
//  LeGou
//
//  Created by lxm on 2022/7/23.
//

import UIKit

class MineVC: ZMViewController {
    //MARK: --------------------属性--------------------
    let padding : CGFloat = 16
    
    var myProfitInfo = ZMUtil.fastNilBehavior(type: MineModels.Profit.self)
    
    var myActicityInfo = ZMUtil.fastNilBehavior(type: MineModels.ActivityInfo.self)
    
    let walletInfo = ZMUtil.fastNilBehavior(type: MineModels.WalletInfo.self)
    //MARK: --------------------UI控件--------------------
    let scrollView = UIScrollView()
    
    let nav = NavigationBarView()
    
    let stack = ZMUtil.stackView(axis: .vertical, spacing: 12)
    
    let avatarView = AvatarContent().then { v in
//        v.backgroundColor = .yellow
    }
    
    let settingBtn = ZMUtil.button(image: UIImage.init(named: "mine_set"))
    
    let serviceBtn = ZMUtil.button(image: UIImage.init(named: "mine_erji"))
    // 共富
    let riceView = AllRiceView()
    
    // 小格子
    let itemsView = MineItemView()
    
    let serviceProfit = ZMUtil.imageView(imageName: "mine_fwsqy")
    
    // 加入群聊
    let joinGroup = ZMUtil.imageView(imageName: "mine_join")
    
    // 我的收益
    let myProfit = MyProfitView()
    
    // 常用功能
    let toolsView = MineBottomCateView()
    //MARK: --------------------生命周期--------------------
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        addConstraints()
        bindAction()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        ZMAppShareData.share.requestUserInfo { ok in
            
        }
        getMyProfit()
        getData()
        loadDate()
    }
    //MARK: --------------------UI--------------------
    func setUI() {
        hbd_barHidden = true
        view.addSubview(scrollView)
        view.addSubview(nav)
        scrollView.addSubview(stack)
        scrollView.backgroundColor = "#F5F5F5".zm.hex()
        view.backgroundColor = "#F5F5F5".zm.hex()
        stack.addArrangedSubview(avatarView)
        stack.distribution = .fill
        stack.alignment = .center
        
        // nav
        let navStack = ZMUtil.stackView(axis: .horizontal, spacing: padding)
        navStack.addArrangedSubview(serviceBtn)
        navStack.addArrangedSubview(settingBtn)
        nav.contentView.addSubview(navStack)
        navStack.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().offset(-padding)
        }
        nav.backButton.isHidden = true
        
        // riceView
        stack.addArrangedSubview(riceView)
        riceView.isHidden = AppHelper.appVerify()

        // itemsView
        stack.addArrangedSubview(itemsView)
        
        //serviceProfit
        stack.addArrangedSubview(serviceProfit)
        serviceProfit.isHidden = AppHelper.appVerify()

        // myProfit
        stack.addArrangedSubview(myProfit)
        myProfit.layer.cornerRadius = 8
        myProfit.backgroundColor = .white
        
        stack.addArrangedSubview(joinGroup)
        
        // toolsView
        stack.addArrangedSubview(toolsView)
    }
    
    
    func addConstraints() {
        nav.snp.makeConstraints { make in
            make.right.left.top.equalToSuperview()
        }
        
        scrollView.snp.makeConstraints { make in
            make.top.equalTo(nav.snp.bottom)
            make.right.bottom.left.equalToSuperview()
        }
        
        stack.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.right.top.left.equalToSuperview()
            make.bottom.equalToSuperview().offset(-padding)
        }
        
        avatarView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.height.equalTo(90)
        }
        
        riceView.snp.makeConstraints { make in
            make.height.equalTo(64)
            make.left.equalToSuperview().offset(padding).priority(.high)
            make.right.equalToSuperview().offset(-padding).priority(.high)
        }
        
        itemsView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(padding).priority(.high)
            make.right.equalToSuperview().offset(-padding).priority(.high)
        }
        
        serviceProfit.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(padding).priority(.high)
            make.right.equalToSuperview().offset(-padding).priority(.high)
            let w = SCREEN_W - padding * 2
            let h = w / 343 * 116
            make.height.equalTo(h)
        }
        
        myProfit.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(padding).priority(.high)
            make.right.equalToSuperview().offset(-padding).priority(.high)
//            make.height.equalTo(173)
        }
        
        joinGroup.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(padding).priority(.high)
            make.right.equalToSuperview().offset(-padding).priority(.high)
            let w = SCREEN_W - padding * 2
            let h = w / 343 * 48
            make.height.equalTo(h)
        }
        
        toolsView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(padding).priority(.high)
            make.right.equalToSuperview().offset(-padding).priority(.high)
        }
    }
    
    //MARK: --------------------methods--------------------
    func bindAction() {
        // 头像点击
        avatarView.avatar.rx.tap.subscribe(onNext:{ [unowned self] resp in
            if !LoginService.shared.checkLogin() {return}
            router.push("xm://main/Mine/user_info")
        }).disposed(by: disposeBag)
        
        // 微信设置
        avatarView.wechatBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
            if !LoginService.shared.checkLogin() {return}
            router.push("xm://main/Mine/set_wx")
        }).disposed(by: disposeBag)
        
        avatarView.fwsIcon.rx.tap.subscribe(onNext:{ [unowned self] resp in
            if !LoginService.shared.checkLogin() {return}
            if let info = ZMAppShareData.share.userInfo.value, info.serviceProviderLevel > 1 {
                router.push("xm://main/Mine/user_level")
            } else {
                CommonService.shared.goWeb(type: .serviceLevelRules)
            }
        }).disposed(by: disposeBag)
        
        avatarView.copyBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
            if !LoginService.shared.checkLogin() {return}
            guard let info = ZMAppShareData.share.userInfo.value else {return}
            UIPasteboard.general.string = info.showId
            ZMToast.showToast(title: "已复制")
        }).disposed(by: disposeBag)
        
        // 共富
        riceView.onClick = { [weak self] type in
//            guard let self = self else {return}
            if !LoginService.shared.checkLogin() {return}
            if type == 0 {
                let v = ZMUtil.loadNibViewFullScreen(nibName: DoTaskView.self)
                APPWindow?.addSubview(v)
            } else {
                router.push("xm://main/Mine/activity_num")
            }
        }
        
        settingBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
            if !LoginService.shared.checkLogin() {return}
            router.push("xm://main/Mine/setting")
        }).disposed(by: disposeBag)
        
        
        serviceBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
            // 客服
            CommonService.shared.showContactService()
        }).disposed(by: disposeBag)
        
        itemsView.onClick = { item in
            if !LoginService.shared.checkLogin() {return}
            if item.id == 1 {
                router.push("xm://main/Mine/mall_order")
            } else if item.id == 2 {
                router.push("xm://main/Mine/other_order")
            } else if item.id == 3 {
                // 我的粉丝
                router.push("xm://main/Mine/my_fans")
            } else if item.id == 4 {
                ZMToast.showToast(title: "敬请期待")
                return
//                router.push("xm://main/Mine/old_account")
            } else if item.id == 5 {
                router.push("xm://main/Mine/invite")
            } else if item.id == 6 {
                ZMLog(message: "积分订单")
                let integralVC = Orders().then { vc in
                    vc.type = .integral
                }
                self.navigationController?.pushViewController(integralVC, animated: true)
            }
        }
        
        // 提现
        myProfit.withDrawButton.rx.tap.subscribe(onNext:{ [unowned self] resp in
            if !LoginService.shared.checkLogin() {return}
            
            if !LoginService.shared.checkRealName() {return}
            
            router.push("xm://main/Mine/withdraw", context: ["type" : 1])
        }).disposed(by: disposeBag)
        
        myProfit.zm.addTap(target: self, selector: #selector(onMyprofit))
        
        toolsView.onClick = { [weak self] item in
            if !LoginService.shared.checkLogin() {return}
            guard let self = self else {return}
            if item.id == 1 {
                if !LoginService.shared.checkRealName() {return}
                router.push("xm://main/Mine/real_name_info")
            } else if item.id == 2 {
                // 合伙人
                router.push("xm://main/Partner/index")
            } else if item.id == 3 {
                // 第三方账户
                router.push("xm://main/Mine/third_account")
            } else if item.id == 4 {
                // 常用地址
                let vc = ZMAddressListVC()
                self.navigationController?.pushViewController(vc, animated: true)
            } else {
                ZMToast.showToast(title: "敬请期待")
            }
        }
        
        let serviceProfitTap = UITapGestureRecognizer(target: self, action: #selector(onServiceProfit))
        serviceProfit.addGestureRecognizer(serviceProfitTap)
        serviceProfit.isUserInteractionEnabled = true
        
        let joinGroupTap = UITapGestureRecognizer(target: self, action: #selector(onJoinGroup))
        joinGroup.addGestureRecognizer(joinGroupTap)
        joinGroup.isUserInteractionEnabled = true
        
        
        ZMAppShareData.share.userInfo.subscribe(onNext:{ [unowned self] resp in
            guard let info = resp else {
                // 未登录
                avatarView.avatar.setImage(UIImage.init(named: "def_user_img"), for: .normal)
                avatarView.name.isHidden = true
                avatarView.fwsIcon.isHidden = true
                avatarView.realNameIcon.isHidden = true
                avatarView.inviteCode.isHidden = true
                avatarView.copyBtn.isHidden = true
//                avatarView.wechatBtn.isHidden = true
                avatarView.wdl.isHidden = false
                avatarView.hehuoren.isHidden = true
                self.myProfitInfo.accept(nil)
                self.myActicityInfo.accept(nil)
                avatarView.ckIcon.isHidden = true
                avatarView.tLevleIcon.isHidden = true
                return
            }
            avatarView.name.isHidden = false
            avatarView.fwsIcon.isHidden = true
            avatarView.realNameIcon.isHidden = info.realName == ""
            avatarView.inviteCode.isHidden = false
            avatarView.copyBtn.isHidden = false
//            avatarView.wechatBtn.isHidden = AppHelper.appVerify()
            avatarView.wdl.isHidden = true
            avatarView.avatar.zm.setImage(urlStr: info.avatar, state: .normal, placeholder: "def_user_img")
            avatarView.inviteCode.text = "推荐码：\(info.showId)"
            avatarView.name.text = info.nickname
            avatarView.fwsIcon.isHidden = AppHelper.appVerify()
            avatarView.ckIcon.isHidden = AppHelper.appVerify()
            avatarView.tLevleIcon.isHidden = AppHelper.appVerify()
            if info.ironArmy {
                avatarView.ckIcon.setImage(UIImage.init(named: "mine_fws_1"), for: .normal)
            } else {
                avatarView.ckIcon.setImage(UIImage.init(named: "level_ck_g"), for: .normal)
            }
            
            if info.serviceProviderLevel > 1 {
                avatarView.fwsIcon.setImage(UIImage(named: "mine_fws_\(info.serviceProviderLevel)"), for: .normal)
            } else {
                avatarView.fwsIcon.setImage(UIImage(named: "mine_fws_1_g"), for: .normal)
            }
            
            if info.teamLevel == 0 {
                avatarView.tLevleIcon.setImage(UIImage.init(named: "level_t_one_g"), for: .normal)
            } else if info.teamLevel == 1 {
                avatarView.tLevleIcon.setImage(UIImage.init(named: "level_t_one"), for: .normal)
            } else if info.teamLevel == 2 {
                avatarView.tLevleIcon.setImage(UIImage.init(named: "level_t_two"), for: .normal)
            } else if info.teamLevel == 3 {
                avatarView.tLevleIcon.setImage(UIImage.init(named: "level_t_three"), for: .normal)
            } else if info.teamLevel == 4 {
                avatarView.tLevleIcon.setImage(UIImage.init(named: "level_t_four"), for: .normal)
            } else if info.teamLevel == 5 {
                avatarView.tLevleIcon.setImage(UIImage.init(named: "level_t_five"), for: .normal)
            } else if info.teamLevel == 6 {
                avatarView.tLevleIcon.setImage(UIImage.init(named: "level_t_six"), for: .normal)
            }
            
            avatarView.hehuoren.isHidden = !info.partnerState
        }).disposed(by: disposeBag)
        
        
        self.myProfitInfo.subscribe(onNext:{ [unowned self] resp in
            if let resp = resp {
                self.myProfit.money.text = resp.nowMoney.zm.toString(keep: 4)
                self.myProfit.one.subTitle.text = resp.totalNowMoney.zm.toString(keep: 4)
                self.myProfit.two.subTitle.text = resp.estimateTodayNowMoney.zm.toString(keep: 4)
                self.myProfit.three.subTitle.text = resp.estimateMonthNowMoney.zm.toString(keep: 4)
            } else {
                self.myProfit.money.text = "0"
                self.myProfit.one.subTitle.text = "0"
                self.myProfit.two.subTitle.text = "0"
                self.myProfit.three.subTitle.text = "0"
            }
        }).disposed(by: disposeBag)
        
        self.walletInfo.subscribe(onNext:{ [unowned self] resp in
            if let resp = resp {
                self.myProfit.titleSub.text = resp.withdrawalDate
            } else {
                self.myProfit.titleSub.text = ""
            }
        }).disposed(by: disposeBag)
        
        self.myActicityInfo.subscribe(onNext:{ [unowned self] resp in
            guard let resp = resp else {
                self.riceView.totalActivity.text = "0"
                self.riceView.todayActivity.text = "0"
                return
            }
            self.riceView.totalActivity.text = resp.teamActivity.zm.toString(keep: 4)
            self.riceView.todayActivity.text = resp.totalActivity.zm.toString(keep: 4)
        }).disposed(by: disposeBag)
        
        avatarView.ckIcon.rx.tap.subscribe(onNext:{ [unowned self] resp in
            CommonService.shared.goWeb(type: .ckIntro)
        }).disposed(by: disposeBag)
        
        avatarView.tLevleIcon.rx.tap.subscribe(onNext:{ [unowned self] resp in
            CommonService.shared.goWeb(type: .tLevelIntro)
        }).disposed(by: disposeBag)
    }
    
    @objc func onMyprofit() {
        if !LoginService.shared.checkLogin() {return}
        if AppHelper.appVerify() {
            let vc = ProfitIndex()
            vc.type = .buySelf
            self.navigationController?.pushViewController(vc, animated: true)
        } else {
            let vc = MyProfit_V2()
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }

    // 服务商升级
    @objc func onServiceProfit() {
        if !LoginService.shared.checkLogin() {return}
//        if ZMAppShareData.share.safeUserInfo.serviceProviderLevel == 0 {
//            ZMAlertView.show(content: "您还没有成为服务商", left: nil, right: "确定") {
//
//            } onRight: {
//
//            }
//
//            return
//        }
        tabBarController?.selectedIndex = 1
//        router.push("xm://main/Mine/user_level")
    }
    
    // 加入群聊
    @objc func onJoinGroup() {
        CommonService.shared.goWeb(type: .wxGroup)
    }
    
    
    func getMyProfit() {
        if ZMAppShareData.share.isLogin == false {
            self.myProfitInfo.accept(nil)
            return
        }
        MineAPI.myProfit.rxRequest(type: MineModels.Profit.self).subscribe(onNext:{ [unowned self] resp in
            self.myProfitInfo.accept(resp)
        }).disposed(by: disposeBag)
    }
    
    func getData() {
        MineAPI.activityData.rxRequest(type: MineModels.ActivityInfo.self).subscribe(onNext:{ [unowned self] resp in
            self.myActicityInfo.accept(resp)
        }, onError: { _ in
            
        }).disposed(by: disposeBag)
    }
    
    func loadDate() {
        let api = MineAPI.walletInfo([:])
        api.rxRequest(type: MineModels.WalletInfo.self).subscribe(onNext:{ [unowned self] resp in
            self.walletInfo.accept(resp)
        }, onError: { e in
        }).disposed(by: disposeBag)
    }
    
    //MARK: --------------------delegate--------------------
}
